<template>
  <view class="oreo">
    <image class="oreo-header" :src="ossImg('personal/oreo_header.png')" />
    <view
      class="oreo-info"
      :style="{ backgroundImage: `url(${ossImg('personal/p1_bg.png')})` }"
    >
      <view class="info" @click.stop="toVipRegister">
        <view
          class="user-avatar"
          @click.stop="linkTo('/personalPages/personalInfo/index')"
          :style="{
            backgroundImage: `url(${
              user.avatar || ossImg('personal/moren_avatar.png')
            })`,
          }"
        ></view>
        <view class="user-nickname">{{ user.nickname }}</view>
      </view>
      <view class="biz-container"> </view>
      <view class="oreo-integral flex">
        <view class="oreo-integral-icon"
          ><image :src="ossImg('personal/oero_binggan.png')"
        /></view>

        <view
          class="integral-Score"
          @click.stop="linkTo('/personalPages/biscuit/biscuit')"
          >{{ user.memberScore.surplusScore }}</view
        >
      </view>
      <view class="sign" @click.stop="linkTo('/personalPages/biscuit/biscuit')">
        <image :src="ossImg('personal/sign.png')" />
        <view class="sign-label">我的饼干</view>
      </view>
    </view>
  </view>
  <view class="oreo-banner">
    <image
      mode="widthFix"
      :src="ossImg('funCard/nfo.png')"
      @click.stop="toFunCard"
    />
    <!-- <image
      mode="widthFix"
      :src="ossImg('personal/gf_pic.png')"
      @click.stop="
        linkTo(
          `/pages/webView/webview?webSrc=${'https://nfo.cocafe.co/home'}&referral=mai&titleName=${'元宇宙NFO展览馆'}`
        )
      "
    /> -->
  </view>
  <view class="oreo-notice">
    <view
      class="notice-content"
      @click.stop="
        linkTo(
          '/pages/webView/webview?webSrc=https://mp.weixin.qq.com/s/T6ThaRY-yimSkm0b2pH2Tg'
        )
      "
    >
      <image :src="ossImg('personal/chick@2x.png')" />
      <view class="content">点击关注奥利奥公众号，解锁更多新玩法</view>
      <image class="oreo-icon" :src="ossImg('personal/aoliao_icon@2x.png')" />
    </view>
  </view>
  <!--  隐私政策更新弹窗  -->
  <privacy-update-dialog
    v-if="state.privacyDialog"
    @close="handleChangePrivacyDialog(false)"
  ></privacy-update-dialog>
  <view class="oreo-menu">
    <view class="oreo-menu__item" @click.stop="handleChangePrivacyDialog(true)">
      <view>
        <image class="icon" style="width: 36rpx; height: 36rpx" :src="ossImg('personal/privacy_dialog/ys_icon.png')" />
        <text class="-ml-1px">隐私政策更新</text>
      </view>
      <image class="arrow" :src="ossImg('personal/go@2x.png')" />
    </view>
    <template v-for="(item, index) in menus" :key="index">
      <view class="oreo-menu__item" @click.stop="linkTo(item.url)">
        <view>
          <image class="icon" :src="item.icon" />
          {{ item.label }}
        </view>
        <image class="arrow" :src="ossImg('personal/go@2x.png')" />
      </view>
    </template>
    <!-- 礼品卡 -->
    <view class="oreo-menu__item" @click.stop="toFunCardByMune()">
      <view>
        <image class="icon" :src="ossImg('funCard/funCard_icon.png')" />
        我的玩心FUN享卡
      </view>
      <image class="arrow" :src="ossImg('personal/go@2x.png')" />
    </view>
    <template v-for="(item, index) in menus_" :key="index">
      <view v-if="item.divider" class="divider"></view>
      <view v-else class="oreo-menu__item" @click.stop="linkTo(item.url)">
        <view>
          <image class="icon" :src="item.icon" />
          {{ item.label }}
        </view>
        <image class="arrow" :src="ossImg('personal/go@2x.png')" />
      </view>
    </template>

    <button open-type="contact" style="padding: 0" @click.stop="toKefu">
      <view class="oreo-menu__item">
        <view>
          <image class="icon" :src="ossImg('personal/lxkf_icon.png')" />
          联系客服
        </view>
        <image class="arrow" :src="ossImg('personal/go@2x.png')" />
      </view>
    </button>
  </view>
  <button open-type="contact" @click.stop="toKefu">
    <view class="oreo-service">
      <image :src="ossImg('personal/kf_icon@2x.png')" />客服
    </view>
  </button>
  <custom-tab-bar :current="5" :cartCount="cartCount" />
  <view class="pb-10px">
    <tab-bar-divider />
  </view>
  <!-- <nfc-card 
    v-model:show="state.nfcShow"
    @success="handleNFCSuccess"
    @error="handleNFCError"
  /> -->
</template>

<script setup>
import { ossImg } from "@/utils/utils";
import { onMounted, reactive, ref } from "vue";
import { onShow, onHide, onLoad } from "@dcloudio/uni-app";
import { wechatUserPhone, bindPhone } from "../../services/utils.js";
import { GetBiscuitInfo } from "@/services/biscuit";
import { setCurrentTabBar } from "@/utils/utils";
import TabBarDivider from "@/components/tab-bar-divider";
import CustomTabBar from "@/components/custom-tab-bar";
import PrivacyUpdateDialog from "@/components/privacyUpdateDialog.vue";
// import NfcCard from "@/components/nfc-card.vue";

const user = reactive({
  nickname: "",
  avatar: "",
  // needBindPhone: false,
  needLogin: false,
  memberScore: {},
  authorizationStatus: false,
})

const state = reactive({
  privacyDialog: false,
  isRegister: false,
  nfcShow: false,
})

const cartCount = ref(getApp().globalData.cartCount);

const loginParam = {
  // 调用 wx.login 时 code
  code: "",
  // 拿个人资料时 昵称
  nickName: "",
  // 拿个人资料时 头像
  avatar: "",
  // 其它诸如性别，城市 微信已作为匿名化处理，不再接收
  // see https://developers.weixin.qq.com/community/develop/doc/00028edbe3c58081e7cc834705b801
  type: 1, // 渠道或终端类型，微信小程序固定 1，微信公众号 固定 2
};

onLoad(() => {
  if ([1011, 1025, 1047, 1105, 1124, 1150, 1017]
    .includes(uni.getLaunchOptionsSync().scene)) {
    state.isRegister = true
  }
});

onShow(() => {
  getUserInfo();
  // 页面切换到前台时
  setCurrentTabBar(4, false);
  getApp()
    .getCartCount()
    .then((res) => {
      cartCount.value = res;
    });
  getApp().accessLogAdd();
});

onHide(() => {
  // 页面切换到后台时
});

// 处理NFC读取成功
const handleNFCSuccess = (data) => {
  uni.showToast({
    title: JSON.stringify(data),
    icon: 'success'
  });
  console.log('NFC数据:', data);
};

// 处理NFC读取错误
const handleNFCError = (error) => {
  console.error('NFC错误:', error);
};

const handleChangePrivacyDialog = (visible) => {
  if (visible) {
    getApp().emdlz2('track','event','Oreo_profile_policy_page','click','renew_policy','');
  } else {
    getApp().emdlz2('track','event','Oreo_profile_policy_page','click','close_tips','');
  }
  state.privacyDialog = visible
}

const getUserInfo = async () => {
  await getApp().getUserLoginInfo()
  GetBiscuitInfo().then((res) => {
    let { code, data } = res;
    if (code == 200) {
      Object.assign(user, data);
      let phone = data.phone;
      user.name = data.nickname;
      user.avatar = data.icon;
      user.memberScore = data.memberScore;
      uni.setStorageSync("USER_INFO", data);
      // if (phone === null || phone === "") {
      //   user.needBindPhone = true;
      // }
      if (state.isRegister && !data.phone) {
        uni.navigateTo({
          url: '/pages/vip/register'
        })
      }
    }
    if (res?.code == 401) {
      user.needLogin = true;
    }
  });
};

const getPhoneNumber = (e) => {
  console.log(e.detail);
  // 结构如下
  /*
    {errMsg: "getPhoneNumber:ok", encryptedData: "...", iv: "...", cloudID: "...", code: "..."}
    */
  // 记录下phone code
  let phoneCode = e.detail.code;
  wechatUserPhone({ code: phoneCode }).then((r) => {
    console.log("电话号码", r);
    // 后续这个接口可能加密
    /*
       {"code":200,"message":"ok","data":{"phoneNumber":"13888888888","purePhoneNumber":"13888888888","countryCode":"86","watermark":{"timestamp":"1658227174","appid":"wx94b544638bc6bc0b"}}}
      */
    if (r?.code == 200) {
      if (r.data.countryCode !== "86") {
        return uni.showToast({
          title: "目前仅支持中国大陆地区手机号",
          icon: "none",
        });
      }
      let phone = r.data.purePhoneNumber;
      bindPhone({ phone: phone }).then((r2) => {
        let { code, data } = r2;
        if (code == 200) {
          if (data == 1) {
            // 绑定手机号成功
            // 可以刷新页面
            user.needBindPhone = fasle;
            return;
          } else if (data == -1) {
            return uni.showToast({
              title: "手机号已被注册，请更换其它手机号",
              icon: "none",
            });
          }
        } else {
          // 绑定失败
          return uni.showToast({
            title: "绑定失败",
            icon: "none",
          });
        }
      });
    } else {
      console.log("拿取微信手机号失败");
    }
  });
};

onMounted(() => {

});

const linkTo = (url) => uni.navigateTo({ url });

const toVipRegister = () => {
  if (
    getApp().globalData.user.phone === null ||
    getApp().globalData.user.phone === ""
  ) {
    uni.setStorageSync("REDIRECT_URI", JSON.stringify({ path }));
    uni.navigateTo({ url: "/pages/vip/register" });
    return;
  }
};

const toKefu = () => {
  getApp().emdlz2("track", "event", "homepage", "click", "customer_service", "");
  getApp().sr().track("start_consult", {
    action_type: "consult_online",
    // more...
  });
};

const toFunCard = () => {
  getApp().emdlz2("track", "event", "member_page", "click", "fc_banner", "");
  linkTo(`/funCard/index`);
};
const toFunCardByMune = () => {
  getApp().emdlz2("track", "event", "member_page", "click", "my_gift_cards", "");
  linkTo(`/funCard/index`);
};

const menus = [
  {
    label: "积分商城",
    icon: ossImg("personal/mall.png"),
    url: "/personalPages/biscuit/mall",
  },
  {
    label: "我的会员权益",
    icon: ossImg("personal/hyqy_icon@2x.png"),
    url: "/pages/vip/vip",
  },
  {
    label: "我的小饼干",
    icon: ossImg("personal/wdxbg_icon@2x.png"),
    url: "/personalPages/biscuit/biscuit",
  },
  {
    label: "我的订单",
    icon: ossImg("personal/order.png"),
    url: "/personalPages/order/index",
  },
  {
    label: "我的优惠券",
    icon: ossImg("personal/wdyhq_icon@2x.png"),
    url: "/personalPages/coupon/coupon",
  },
];
const menus_ = [
  { divider: true },
  {
    label: "地址管理",
    icon: ossImg("personal/wddz_icon@2x.png"),
    url: "/pages/address/address",
  },
  {
    label: "退货退款政策",
    icon: ossImg("personal/thtk_icon@2x.png"),
    url: "/pages/exchangeClause/index",
  },
  { divider: true },
  {
    label: "隐私条款",
    icon: ossImg("personal/thtk_icon@2x.png"),
    url: "/pages/privacyPolicy/index",
  },
];
</script>

<style lang="less" scoped>
image {
  display: block;
}

.oreo {
  background-color: #4b72bb;

  .oreo-header {
    width: 100%;
    height: 80px;
    position: relative;
    z-index: 1;
  }

  .oreo-info {
    width: 100%;
    height: 318rpx;
    margin-top: 6px;
    background-color: #4b72bb;
    background-repeat: no-repeat;
    background-position: top;
    background-size: 100%;
    position: relative;

    .info {
      display: flex;
      align-items: center;
      box-sizing: border-box;
      padding: 45rpx 50rpx 0 50rpx;

      .user-avatar {
        width: 134rpx;
        height: 134rpx;
        box-sizing: border-box;
        border: 8rpx solid #4b72bb;
        border-radius: 134rpx;
        background-color: white;
        margin-right: 23rpx;
        background-repeat: no-repeat;
        background-position: top;
        background-size: cover;
      }

      .user-nickname {
        color: #45494c;
        font-size: 36rpx;
        font-weight: bold;
      }
    }

    .oreo-integral {
      position: absolute;
      width: 165px;
      left: 374rpx;
      justify-content: center;
      bottom: 123rpx;
      color: #205ac5;
      font-size: 76rpx;
      line-height: 56rpx;
      font-weight: bold;

      .oreo-integral-icon {
        width: 45px;
        height: 31px;
        image {
          width: 100%;
          height: 100%;
        }
      }
    }

    .sign {
      position: absolute;
      color: #ffd74e;
      width: 184rpx;
      height: 162rpx;
      right: 80rpx;
      top: -48rpx;
      display: flex;
      align-items: flex-end;
      padding-bottom: 28rpx;
      box-sizing: border-box;

      image {
        width: inherit;
        height: inherit;
        position: absolute;
        top: 0;
        z-index: 0;
      }

      .sign-label {
        width: 100%;
        position: relative;
        z-index: 1;
        text-align: center;
        line-height: 1;
      }
    }
  }
}

.oreo-banner {
  margin-top: 10rpx;
  padding: 20rpx;
  box-sizing: border-box;
  background: white;

  image {
    width: 100%;
  }
}

.oreo-notice {
  box-sizing: border-box;
  padding: 20rpx;
  background-color: white;
  margin: 20rpx 0;

  .notice-content {
    width: 100%;
    height: 80rpx;
    border: 4rpx solid #205ac5;
    color: #205ac5;
    border-radius: 80rpx;
    box-sizing: border-box;
    font-size: 26rpx;
    display: flex;
    align-items: center;
    padding: 0 28rpx 0 54rpx;

    .content {
      flex: 1;
      box-sizing: border-box;
      padding: 0 16rpx;
      line-height: 1;
    }

    image {
      &:nth-child(1) {
        width: 46rpx;
        height: 56rpx;
      }

      &.oreo-icon {
        width: 50rpx;
        height: 41rpx;
      }
    }
  }
}

.oreo-menu {
  .divider {
    width: 100%;
    height: 10px;
  }

  .oreo-menu__item {
    width: 100%;
    height: 97rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    border-bottom: 2rpx solid #e5e5e5;
    padding: 0 30rpx 0 0;
    font-size: 28rpx;
    background: white;

    & > view {
      display: flex;
      align-items: center;
      color: #3e3e3e;
      font-weight: 500;
    }

    .icon {
      width: 32rpx;
      height: 32rpx;
      margin: 23rpx;
    }

    .arrow {
      width: 10rpx;
      height: 18rpx;
    }
  }
}
</style>
